<template>
  <el-drawer size="45%" :visible.sync="drawer" :with-header="false" :width="900" direction="rtl">
    <div class="drawer_box">
      <div class="drawer_t">
        <div class="drawer_t_l">
          <img class="drawer_t_l_img" src="/static/skin/herodoo/main/platform/home/img/piliangoumai.png" alt="" />
          编辑活动
        </div>
        <img class="drawer_t_r" src="/static/skin/herodoo/main/platform/home/img/guanbi.png" alt=""
          @click="drawer = false" />
      </div>
      <div class="drawer_c">
        <div class="drawer_content">
          <!-- <div class="con-title">基本信息</div> -->
          <div class="content-box">
            <div class="label">活动主图：</div>
            <div class="desc">
              <div class="tips">
                主图仅可上传1张图片，图片不超过512KB，仅支持jpg、png格式建议尺寸16：9
              </div>
              <update ref="update" :list="mainUrlList" :num="1" :octopus="octopus" @imgList="getMainUrl"></update>
            </div>
          </div>
          <div class="content-box">
            <div class="label">活动附图：</div>
            <div class="desc">
              <div class="tips">
                附图可上传3张图片，单张图片不超过512KB，仅支持jpg、png格式建议尺寸16：9
              </div>
              <update ref="updateFigures" multiple :list="imgsUrlList" @imgList="getImgsUrl" :num="3"
                :octopus="octopus">
              </update>
            </div>
          </div>
          <div class="content-box">
            <div class="label">所属项目:</div>
            <div class="desc">
              <el-select v-model="form.Source" clearable placeholder="请选择新闻来源">
                <el-option v-for="item in sourceList" :key="item.ID" :label="item.Name" :value="item.ID">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="content-box">
            <div class="label">活动标题：</div>
            <div class="desc">
              <el-input v-model="form.Name" placeholder="请输入活动标题">
              </el-input>
            </div>
          </div>
          <!-- 活动经纬度 -->
          <div class="content-box">
            <div class="label">活动经纬度：</div>
            <div class="desc">
              <div class="row">
                <span>活动地点经度：</span>
                <el-input v-model="form.XAxis" class="axis w40" placeholder="请输入活动地点经度"></el-input>
              </div>
              <div class="row">
                <span>活动地点纬度：</span>
                <el-input v-model="form.YAxis" class="axis w40" placeholder="请输入活动地点纬度"></el-input>
              </div>
            </div>
          </div>

          <div class="content-box">
            <div class="label">活动地址：</div>
            <div class="desc">
              <el-input v-model="form.Address" placeholder="请输入活动地址">
              </el-input>
            </div>
          </div>
          <div class="content-box">
            <div class="label">是否需要报名：</div>
            <div class="desc">
              <el-radio v-model="form.IsRegistration" :label="1">是</el-radio>
              <el-radio v-model="form.IsRegistration" :label="0">否</el-radio>
            </div>
          </div>

          <template v-if="form.IsRegistration == 1">
            <div class="content-box">
              <div class="label">活动容纳人数:</div>
              <div class="desc">
                <el-input v-model="form.Accommodate" placeholder="请输入活动容纳人数">
                </el-input>
              </div>
            </div>
            <!-- 报名时间 -->
            <div class="content-box">
              <div class="label">报名时间:</div>
              <div class="content flex">
                <el-date-picker v-model="form.RegistrationStartTime" type="datetime" placeholder="选择报名开始日期时间">
                </el-date-picker>
                <span style="padding: 0 10px;">至</span>
                <el-date-picker v-model="form.RegistrationEndTime" type="datetime" placeholder="选择报名结束日期时间">
                </el-date-picker>
              </div>
            </div>
          </template>

          <!-- 活动时间 -->
          <div class="content-box">
            <div class="label">活动时间:</div>
            <div class="content flex">
              <el-date-picker v-model="form.StartTime" type="datetime" placeholder="选择活动开始日期时间">
              </el-date-picker>
              <span style="padding: 0 10px;">至</span>
              <el-date-picker v-model="form.EndTime" type="datetime" placeholder="选择活动结束日期时间">
              </el-date-picker>
            </div>
          </div>

          <div class="content-box flex-column">
            <div class="label">活动介绍：</div>
            <div class="desc">
              <quill ref="quill" v-if="drawer" :octopus="octopus" :desc="quillContent" @quillContent="getQuillContent">
              </quill>
            </div>
          </div>
        </div>
        <!-- <div class="footer">
          <button class="footer-btn save" @click="submit(0)">保存</button>
          <button class="footer-btn" @click="submit(2)">发布</button>
        </div> -->
        <div class="button_list">
          <button class="footer-btn save" style="background-color: #1E1B19;" @click="save(0)">暂存</button>
          <button class="footer-btn" @click="save(1)">发布</button>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import update from "@/components/Components/imgUpdate.vue";
import quill from "@/components/Components/quillEditor.vue";
export default {
  components: {
    update,
    quill
  },
  props: {
    activityId: {
      type: [String, Number],
      default: ""
    },
    messageList: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      octopus: this.$parent.octopus,
      drawer: false,
      form: {
        Source: '',
        Name: "",
        Address: "",
        IsRegistration: 1,
        RegistrationStartTime: "",
        RegistrationEndTime: "",
        StartTime: "",
        EndTime: "",
        Accommodate: "",
        Description: "",
        MainPicturePath: [],
        SecondaryPicturePath: [],
        TypeID: "",
        XAxis: "",
        YAxis: "",
        ID: ""
      },
      mainUrlList: [],
      imgsUrlList: [],
      quillContent: "",
      rules: {
        MainPicturePath: { required: false, message: "请上传一张活动图片" },
        SecondaryPicturePath: { required: false, message: "请上传1~3张图片" },
        Source: { required: true, message: "请选择所属项目" },
        Name: { required: true, message: "请输入活动标题" },
        XAxis: {
          required: true,
          message: "请正确输入活动经度",
          reg: /^\d+(\.\d{1,6})?$/
        },
        YAxis: {
          required: true,
          message: "请正确输入活动纬度",
          reg: /^\d+(\.\d{1,6})?$/
        },
        Address: { required: true, message: "请填写活动地址" },
        Description: { required: true, message: "请填写活动介绍" }
        // RegistrationStartTime: { required: true, message: "请选择活动报名开始时间"},
        // RegistrationEndTime: { required: true, message: "活动报名结束时间必须大于活动报名开始时间", reg: ()=> {
        //   let start = new Date(this.form.RegistrationStartTime).getTime()
        //   let end = new Date(this.form.RegistrationEndTime).getTime()
        //   return end > start
        // }},
        // StartTime: { required: true, message: "请选择活动开始时间"},
        // EndTime: { required: true, message: "请选择活动结束时间"},
        // TypeID: { required: false, message: "请选择活动类别" },
      },
      sourceList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      }
    };
  },
  watch: {
    drawer: {
      handler(v) {
        this.quillContent = "";
        if (v) {
          this.form = {
            Source: '',
            Name: "",
            Address: "",
            IsRegistration: 1,
            RegistrationStartTime: "",
            RegistrationEndTime: "",
            StartTime: "",
            EndTime: "",
            Accommodate: "",
            Description: "",
            MainPicturePath: [],
            SecondaryPicturePath: [],
            TypeID: "",
            XAxis: "",
            YAxis: "",
            ID: ""
          };
          this.mainUrlList = [];
          this.imgsUrlList = [];
          this.api_1415();
          this.activityId && this.getActivityInfo();
        }
      }
    }
  },

  computed: {},
  methods: {
    showDialog() {
      this.drawer = true;
      this.quillContent = "";

    },
    closeDialog() {
      this.drawer = false;
    },
    getActivityInfo() {
      this.octopus.request.api.post(
        "/Octopus/Engine/List",
        {
          id: 1341,
          cellData: [
            { name: "Name" }, // 活动名称|标题
            { name: "Address" }, // 活动地址（详情地址）
            { name: "IsRegistration" }, // 是否需要报名 （0否   1是 ）
            { name: "RegistrationStartTime" }, // 报名开始时间
            { name: "RegistrationEndTime" }, // 报名结束时间
            { name: "StartTime" }, // 活动开始时间
            { name: "EndTime" }, // 活动结束时间
            { name: "CreateTime" }, // 创建时间
            { name: "Accommodate" }, // 活动容纳人数
            { name: "CreateUserID" }, // 创建人
            { name: "Description" }, // 活动介绍
            { name: "MainPicturePath" }, // 主图URL（1张）
            { name: "PvCount" }, // 浏览量
            { name: "SecondaryPicturePath" }, // 附图URL（3张）
            { name: "TypeID" }, // 活动类别
            { name: "UpdateTime" }, // 维护时间
            { name: "UpdateUserID" }, // 维护人
            { name: "XAxis" }, // 活动地址经度
            { name: "YAxis" }, // 活动地址纬度
            { name: "ProjectID" },	// 项目ID
            { name: "ID", filterKey: "=", filterValue: this.activityId } // ID
          ]
        },
        data => {
          if (data.status.code == 200) {
            this.form = data.content.queryData[0];
            this.form.IsRegistration == "是" && (this.form.IsRegistration = 1);
            this.form.IsRegistration == "否" && (this.form.IsRegistration = 0);
            this.quillContent = this.form.Description;
            // this.$nextTick(()=> this.$refs.quill.content = this.form.Description)
            try {
              this.mainUrlList = JSON.parse(this.form.MainPicturePath);
              this.imgsUrlList = JSON.parse(this.form.SecondaryPicturePath);
            } catch (e) { }
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },

    getQuillContent(content) {
      this.form.Description = content;
    },
    getMainUrl(fileList) {
      this.form.MainPicturePath = fileList;
      this.mainUrlList = fileList;
    },
    getImgsUrl(fileList) {
      this.form.SecondaryPicturePath = fileList;
      this.imgsUrlList = fileList;
    },
    save(status) {
      if (!this.octopus.tools.verify(this.form, this.rules)) {
        return;
      }

      if (this.form.StartTime == "") {
        this.octopus.tips.warning("请选择活动开始时间");
        return;
      }
      if (this.form.EndTime == "") {
        this.octopus.tips.warning("请选择活动结束时间");
        return;
      }
      let start = new Date(this.form.StartTime).getTime();
      let end = new Date(this.form.EndTime).getTime();

      if (this.form.IsRegistration) {
        let accReg = /^\d+$/;
        if (!accReg.test(this.form.Accommodate)) {
          this.octopus.tips.warning("请输入活动容纳人数");
          return;
        }
        if (this.form.RegistrationStartTime == "") {
          this.octopus.tips.warning("请选择活动报名开始时间");
          return;
        }
        if (this.form.RegistrationEndTime == "") {
          this.octopus.tips.warning("请选择活动报名结束时间");
          return;
        }
        let regStart = new Date(this.form.RegistrationStartTime).getTime();
        let regEnd = new Date(this.form.RegistrationEndTime).getTime();
        if (regEnd <= regStart) {
          this.octopus.tips.warning("活动报名结束时间必须大于活动报名开始时间");
          return;
        }
        if (start < regEnd) {
          this.octopus.tips.warning("活动开始时间不能在报名结束时间之前");
          return;
        }
        if (end <= start) {
          this.octopus.tips.warning("活动结束时间必须大于活动开始时间");
          return;
        }
        this.form.RegistrationStartTime = this.format(
          this.form.RegistrationStartTime
        );
        this.form.RegistrationEndTime = this.format(
          this.form.RegistrationEndTime
        );
      }
      this.form.MainPicturePath = JSON.stringify(this.mainUrlList);
      this.form.SecondaryPicturePath = JSON.stringify(this.imgsUrlList);
      this.form.StartTime = this.format(this.form.StartTime);
      this.form.EndTime = this.format(this.form.EndTime);
      let txt = status == 0 ? '保存' :'发布';
      this.$confirm(`确定要${txt}该活动吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.submit(status);
        })
        .catch(() => {
          console.log("取消了");
        });
    },
    // 提交创建/修改
    submit(status) {

      let type = "CREATE";
      if (this.form.ID) {
        type = "UPDATE";
      }
      const cellData = [
        { name: "ProjectID", defaultValue: this.form.Source },	// 项目ID
        { name: "Name", defaultValue: this.form.Name }, // 活动名称|标题
        { name: "Address", defaultValue: this.form.Address }, // 活动地址（详情地址）
        { name: "IsRegistration", defaultValue: this.form.IsRegistration }, // 是否需要报名 （0否   1是 ）
        { name: "StartTime", defaultValue: this.form.StartTime }, // 活动开始时间
        { name: "EndTime", defaultValue: this.form.EndTime }, // 活动结束时间
        {
          name: "SecondaryPicturePath",
          defaultValue: this.form.SecondaryPicturePath
        }, // 附图URL（3张）
        { name: "Description", defaultValue: this.form.Description }, // 活动介绍
        { name: "MainPicturePath", defaultValue: this.form.MainPicturePath }, // 主图URL（1张）
        { name: "XAxis", defaultValue: this.form.XAxis }, // 活动地址经度
        { name: "YAxis", defaultValue: this.form.YAxis }, // 活动地址纬度
        { name: "Status", defaultValue: status } //活动状态
      ];
      if (this.form.ID) {
        cellData.push({
          name: "UpdateTime",
          defaultValue: this.format(new Date())
        });
        cellData.push({
          name: "UpdateUserID",
          defaultValue: this.octopus.passport.id
        });
      } else {
        cellData.push({
          name: "CreateTime",
          defaultValue: this.format(new Date())
        });
        cellData.push({
          name: "CreateUserID",
          defaultValue: this.octopus.passport.id
        });
        cellData.push({ name: "PvCount", defaultValue: 0 }); // 浏览量
      }
      if (this.form.IsRegistration) {
        cellData.push({
          name: "Accommodate",
          defaultValue: this.form.Accommodate
        }); // 活动容纳人数
        cellData.push({
          name: "RegistrationStartTime",
          defaultValue: this.form.RegistrationStartTime
        }); // 报名开始时间
        cellData.push({
          name: "RegistrationEndTime",
          defaultValue: this.form.RegistrationEndTime
        }); // 报名结束时间
      }
      // return
      this.octopus.request.api.post(
        "/Octopus/Engine/Item",
        {
          id: 1341,
          type,
          value: this.form.ID,
          cellData
        },
        data => {
          if (data.status.code == 200) {
            this.octopus.tips.success(this.form.ID ? "修改" : "创建" + "成功");
            this.drawer = false;
            this.$emit("refresh");
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },

    // 格式化时间
    format(time, format = "yyyy-mm-dd hh:ii:ss") {
      let t = "";
      let f = "";
      if (Object.prototype.toString.call(time) === "[object Object]") {
        t = time.time;
        f = time.format || "yyyy-mm-dd hh:ii:ss";
      } else {
        t = time;
        f = format;
      }
      const d = new Date(t);
      const formatObj = {
        y: d.getFullYear(),
        m: d.getMonth() + 1,
        d: d.getDate(),
        h: d.getHours(),
        i: d.getMinutes(),
        s: d.getSeconds(),
        z: d.getMilliseconds()
      };
      return f.toLowerCase().replace(/([ymdhisaz])+/g, (result, key) => {
        const value = formatObj[key].toString();
        if (key === "y") {
          return value.substr(
            value.length - result.length > 0 && value.length - result.length
          );
        }
        return value.padStart(result.length, "0");
      });
    },
    api_1415() {
      this.octopus.request.api.post(
        "/Octopus/Engine/List",
        {
          id: 1415,
          cellData: [
            { name: "ID" },	// ID
            { name: "Name" },	// Name
          ],
          paramData: {}
        },
        data => {
          if (data.status.code == 200) {
            this.sourceList = data.content.queryData;
            this.form.Source = this.messageList.ProjectID//this.sourceList.find(x=> x.ID == this.messageList.ProjectID).ID//list.row.SourceID;
          } else {
            this.octopus.tips.error(data);
          }
        }
      );
    },
  }
};
</script>
<style scoped>
.button_list {
  margin-top: 1rem;
  display: flex;
  justify-content: end;
  position: absolute;
  background-color: #ffff;
  bottom: 1rem;
  width: calc(100% - 7rem);
}

.button_list button {
  border: none;
  height: 4rem;
  width: 12rem;
  border-radius: 1rem;
  margin-left: 1rem;
  color: #ffff;
  background-color: #f78c53;
  cursor: pointer;
}

.tips {
  margin-bottom: 20px;
}

.drawer_box {
  padding: 3rem 0.8rem 3rem 0;
  height: calc(100% - 5rem);
  display: flex;
  flex-direction: column;
}

.drawer_title {
  box-shadow: 0px 5px 5px rgb(230 228 228 / 30%);
  padding-bottom: 1rem;
  font-size: 1.6rem;
}

.drawer_t {
  padding: 0 2.8rem;
  display: flex;
  justify-content: space-between;
}

.drawer_t_l {
  display: flex;
  align-items: center;
  font-size: 2rem;
  font-weight: bold;
}

.drawer_t_l_img {
  width: 2.8rem;
  margin-right: 1rem;
}

.drawer_t_r {
  width: 3rem;
  height: 3rem;
  cursor: pointer;
}

.button_box {
  margin-top: 1rem;
  padding: 0 3rem;
  display: flex;
}

.drawer_content {
  overflow-y: auto;
  margin-top: 1.5rem;
  height: calc(100vh - 11rem);
  padding: 0 3rem;
  width: 100%;
  padding-bottom: 1rem;
}

.drawer_content .title {
  font-size: 1.8rem;
  font-weight: bold;
}

.drawer_content .driver-title {
  margin-top: 1em;
}

.content-box {
  display: flex;
  align-items: flex-start;
  margin: 2rem 0 2rem 2em;
}

.mt-10 {
  margin-top: 10rem;
}

.content-box .label {
  width: 25%;
  font-size: 1.6rem;
}

.content-box .label .label-bold {
  font-size: 1.8rem;
  font-weight: bold;
}

.content-box .desc {
  flex: 1;
  font-size: 1.6rem;
  padding-left: 2px;
}

>>>.el-radio__input.is-checked+.el-radio__label {
  color: #f87338;
}

>>>.el-radio__input.is-checked .el-radio__inner {
  border-color: #f87338;
  background: #f87338;
}

.w40 {
  width: 70%;
  margin-bottom: 10px;
}
</style>
